<script setup lang="ts">

import {ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {showFailToast, showToast} from "vant";
import {login} from "@/api/login.ts";

const route = useRoute()
const router = useRouter()
const userAccount = ref('');
const userPassword = ref('');
const onSubmit = async () => {
  const {data:res} = await login(userAccount.value,userPassword.value)
  if(res.code === 0 && res.data ){
    sessionStorage.setItem("token", res.data)
    showToast('登录成功！')
    await router.replace(route?.query?.redirect as string ?? '/')
    window.location.reload();
  }else {
    showFailToast('登录失败！'+ res.description)
  }
}
</script>

<template>
  <van-nav-bar title="账号登录" left-text="返回主页" @click-left="$router.replace('/')" left-arrow>
  </van-nav-bar>
  <van-row justify="center">
    <van-image
      height="200px"
      fit="contain"
      width="100%"
      src="http://se837qsbo.hn-bkt.clouddn.com/logo.jpg"
    />
  </van-row>
  <h3 style="text-align: center;">桃友——寻志同道合之友</h3>
  <van-row justify="center">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="userAccount"
            name="账号"
            label="账号"
            placeholder="账号"
            :rules="[{ required: true, message: '请填写账号' }]"
        />
        <van-field
            v-model="userPassword"
            type="password"
            name="密码"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div class="link">
        <RouterLink class="gorget" to="/forget">忘记密码？</RouterLink>
        <RouterLink class="register" to="/regist">还没账号？去注册</RouterLink>
      </div>
      <div style="margin: 20px;">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    
  </van-row>
  
</template>

<style scoped>
.link{
  margin: 1px 16px;
}
.gorget{
    text-decoration: underline; 
    font-size: 2vh; 
}
.register{
  float: right;
  text-decoration: underline; 
    font-size: 2vh; 
}
</style>